package cn.etynit.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 返回值类型就是标识当前过滤器是属于哪个过滤器类型，也就是执行时机
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 该过滤器的执行顺序，返回值越低执行顺序越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 该方法指定是否需要执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        // 2.判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        // 3.如果不包含那么说明用户访问的资源是受保护的资源，那么需要执行登录校验
        return true;
    }

    /**
     * 检查是否有token
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 1.获取到请求头，响应头
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 2.得到请求头中的token信息
        String token = currentContext.getRequest().getHeader("token");
        // 3.判断token等于null
        if (StringUtils.isEmpty(token)){
            // 1.响应未登录提升信息给前端
            try {
                // 1.设置响应信息
                HttpServletResponse response = currentContext.getResponse();
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "请登录！");
                map.put("resultObj", "noLogin");
                String resultJsonStr = JSONObject.toJSONString(map);
                writer.write(resultJsonStr);
                writer.close();
                // 2.切断后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        // 此方法的返回值不用管
        return null;
    }
}
